package com.engr.lyx.auth.biz.service.impl;

import com.engr.lyx.auth.biz.service.feign.UserClient;
import com.engr.lyx.base.client.vo.UserVO;
import com.engr.lyx.common.base.ResultBody;
import com.engr.lyx.common.consts.ResultCodes;
import com.engr.lyx.common.security.UserProfileDetails;
import com.engr.lyx.common.utils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Map;

/**
 * @program:
 * @desc: security 用户实现类
 * @author: lyx
 * @date: 2018-11-28 15:59
 **/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserClient userClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        ResultBody<UserVO> resp = userClient.login(username);
        UserVO user = resp.getData();
        if (resp.getCode() != ResultCodes.SUCCESS) {
            throw new UsernameNotFoundException("Could not found user " + username);
        }
        Collection<String> authorities = user.getAuthorities();
        // 对象转换成map
        Map userProfile = BeanUtils.objectToMap(user);
        return new UserProfileDetails(userProfile, user.getId(), user.getUsername(), user.getPassword(), authorities, true, true, true, true);
    }
}
